package com.youbug.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.youbug.system.entity.Role;
import com.youbug.system.entity.UserRole;
import com.youbug.system.mapper.RoleMapper;
import com.youbug.system.service.IRoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.youbug.system.service.IUserRoleService;
import com.youbug.system.vo.RoleVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 角色表 服务实现类
 * </p>
 *
 * @author apu
 * @since 2022-12-08
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements IRoleService {
    @Autowired
    private IUserRoleService userRoleService;

    @Override
    public IPage<Role> getRolePage(RoleVo roleVo) {

        Page<Role> rolePage = new Page<>();

        rolePage.setCurrent(roleVo.getCurrentPage());

        rolePage.setSize(roleVo.getPageSize());

        QueryWrapper<Role> wrapper = new QueryWrapper<>();

        if(StringUtils.hasText(roleVo.getName())){

            wrapper.like("name", roleVo.getName());
        }
        Page<Role> page = this.page(rolePage, wrapper);

        return page;
    }

    @Override
    public IPage<Role> getRoleOnUser(RoleVo roleVo) {

        IPage<Role> rolePage = this.getRolePage(roleVo);

        List<Long> roleIds = rolePage.getRecords().stream().map(Role::getId).collect(Collectors.toList());

        List<Long> checkRoleIds = userRoleService.list(new QueryWrapper<UserRole>().eq("user_id", roleVo.getUserId())
                .in("role_id", roleIds)).stream().map(UserRole::getRoleId).collect(Collectors.toList());

        rolePage.getRecords().forEach(role -> {
            if(checkRoleIds.contains(role.getId())){
                role.setHave("1");
            }else{
                role.setHave("0");
            }
        });
        return rolePage;
    }

    @Override
    public boolean addRoleOnUser(Long roleId, Long userId) {

        boolean remove = userRoleService.remove(new QueryWrapper<UserRole>().eq("role_id", userId).eq("user_id", userId));
        UserRole userRole = new UserRole();
        userRole.setRoleId(roleId);
        userRole.setUserId(userId);
        boolean save = userRoleService.save(userRole);

        return save;
    }

    @Override
    public boolean removeRoleOnUser(Long roleId, Long userId) {

        boolean remove = userRoleService.remove(new QueryWrapper<UserRole>().eq("role_id", roleId).eq("user_id", userId));

        return remove;
    }
}
